﻿using System;
using System.Data.Entity;
using System.Linq;

namespace TestApplication.Domain.Models.Abstract
{
    public abstract class RepositoryAbstract<T> where T : Entity
    {
        protected DbSet<T> EntitySet { get; set; }

        protected DbContext DbContext;

        protected RepositoryAbstract(DbContext context)
        {
            DbContext = context;
        }

        public virtual IQueryable<T> AsQueryable
        {
            get { return EntitySet.AsQueryable(); }
        }

        public virtual void Add(T entity)
        {
            EntitySet.Add(entity);
        }

        public virtual void Remove(T entity)
        {
            EntitySet.Remove(entity);
        }

        public virtual void Remove(int id)
        {
            var entity = (T) Activator.CreateInstance(typeof (T));
            entity.Id = id;
            DbContext.Entry(entity).State = EntityState.Deleted;
        }

        public virtual void Update(T entity)
        {
            DbContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual T Find(int? id)
        {
            return EntitySet.Find(id);
        }

        public virtual bool IsExists(int? id)
        {
            return EntitySet.Count(e => e.Id == id) > 0;
        }

        public virtual void SaveChanges()
        {
            DbContext.SaveChanges();
        }
    }
}
